package icom.icss.controller;

import icom.icss.entity.User;
import icom.icss.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");


        UserServiceImpl userService = new UserServiceImpl();
        User user=null;

        try {

             user = userService.login(username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
          if(user!=null){
              //获取session 对象
              HttpSession session = request.getSession();
              session.setAttribute("userLogin",user);
              // 记住密码 设置
              String autoLogin = request.getParameter("autoLogin");
              if ("auto".equals(autoLogin)){
                  Cookie autoboxingInfo = new Cookie("autoboxingInfo", URLEncoder.encode(user.getUsername()) + ":" + URLEncoder.encode(user.getPassword()));

                  autoboxingInfo.setMaxAge(60*5);

                  response.addCookie(autoboxingInfo);

              }
              response.sendRedirect("index.jsp");
          }else{
              request.setAttribute("loginInfo", "用户名或密码错误！");
              request.getRequestDispatcher("log_in.jsp").forward(request,response);
          }



    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doPost(request,response);
    }
}
